#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const os = require('os');

// 手动FFmpeg安装脚本
// 用于处理本地FFmpeg安装包

const PLATFORM_CONFIG = {
  win32: {
    binaryName: 'ffmpeg.exe',
    supportedFormats: ['.zip'],
    searchPatterns: [
      'ffmpeg-windows.zip',
      'ffmpeg-win64.zip',
      'ffmpeg-master-latest-win64-gpl.zip',
      'ffmpeg-*.zip'
    ]
  },
  linux: {
    binaryName: 'ffmpeg',
    supportedFormats: ['.tar.xz', '.tar.gz', '.tgz', '.zip'],
    searchPatterns: [
      'ffmpeg-linux.tar.xz',
      'ffmpeg-linux64.tar.xz',
      'ffmpeg-master-latest-linux64-gpl.tar.xz',
      'ffmpeg-linux.tar.gz',
      'ffmpeg-linux64.tar.gz',
      'ffmpeg-*.tar.xz',
      'ffmpeg-*.tar.gz',
      'ffmpeg-*.zip'
    ]
  },
  darwin: {
    binaryName: 'ffmpeg',
    supportedFormats: ['.zip', '.tar.gz', '.tgz'],
    searchPatterns: [
      'ffmpeg-macos.zip',
      'ffmpeg-mac.zip',
      'ffmpeg-osx.zip',
      'ffmpeg-*.zip',
      'ffmpeg-*.tar.gz'
    ]
  }
};

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function logError(message) {
  log(`❌ ${message}`, 'red');
}

function logSuccess(message) {
  log(`✅ ${message}`, 'green');
}

function logInfo(message) {
  log(`ℹ️  ${message}`, 'blue');
}

function logWarning(message) {
  log(`⚠️  ${message}`, 'yellow');
}

// 查找本地FFmpeg安装包
function findLocalPackages() {
  const platform = process.platform;
  const config = PLATFORM_CONFIG[platform];
  
  if (!config) {
    logError(`不支持的操作系统: ${platform}`);
    return [];
  }
  
  const searchPaths = [
    path.join(process.cwd(), 'ffmpeg-packages'),
    path.join(process.cwd(), 'packages'),
    path.join(process.cwd(), 'assets'),
    path.join(process.cwd(), 'binaries', 'packages'),
    path.join(__dirname, '..', 'ffmpeg-packages'),
    path.join(__dirname, '..', 'packages'),
    path.join(__dirname, '..', 'assets')
  ];
  
  const foundPackages = [];
  
  for (const basePath of searchPaths) {
    if (fs.existsSync(basePath)) {
      logInfo(`搜索目录: ${basePath}`);
      
      try {
        const files = fs.readdirSync(basePath);
        
        for (const file of files) {
          const filePath = path.join(basePath, file);
          const stats = fs.statSync(filePath);
          
          if (stats.isFile()) {
            const ext = path.extname(file).toLowerCase();
            if (config.supportedFormats.includes(ext)) {
              // 检查文件名是否匹配模式
              const matchesPattern = config.searchPatterns.some(pattern => {
                const regex = pattern.replace(/\*/g, '.*');
                return new RegExp(regex, 'i').test(file);
              });
              
              if (matchesPattern) {
                foundPackages.push({
                  path: filePath,
                  name: file,
                  size: (stats.size / 1024 / 1024).toFixed(2) + ' MB'
                });
              }
            }
          }
        }
      } catch (error) {
        logWarning(`无法读取目录 ${basePath}: ${error.message}`);
      }
    }
  }
  
  return foundPackages;
}

// 解压文件
function extractPackage(packagePath, extractDir) {
  const platform = process.platform;
  const fileExt = path.extname(packagePath).toLowerCase();
  
  logInfo(`解压文件: ${path.basename(packagePath)}`);
  
  try {
    if (platform === 'win32') {
      // Windows使用PowerShell解压
      const { spawn } = require('child_process');
      
      return new Promise((resolve, reject) => {
        const unzip = spawn('powershell', [
          'Expand-Archive',
          '-Path', packagePath,
          '-DestinationPath', extractDir,
          '-Force'
        ]);
        
        unzip.on('close', (code) => {
          if (code === 0) {
            logSuccess('解压完成');
            resolve();
          } else {
            reject(new Error(`解压失败，退出码: ${code}`));
          }
        });
        
        unzip.on('error', reject);
      });
    } else {
      // Linux/macOS使用系统命令解压
      let extractCommand;
      
      if (fileExt === '.tar.xz') {
        extractCommand = `tar -xf "${packagePath}" -C "${extractDir}"`;
      } else if (fileExt === '.tar.gz' || fileExt === '.tgz') {
        extractCommand = `tar -xzf "${packagePath}" -C "${extractDir}"`;
      } else if (fileExt === '.zip') {
        extractCommand = `unzip -o "${packagePath}" -d "${extractDir}"`;
      } else {
        throw new Error(`不支持的文件格式: ${fileExt}`);
      }
      
      execSync(extractCommand, { stdio: 'inherit' });
      logSuccess('解压完成');
    }
  } catch (error) {
    throw new Error(`解压失败: ${error.message}`);
  }
}

// 查找FFmpeg二进制文件
function findFFmpegBinary(extractDir, binaryName) {
  const searchPaths = [
    path.join(extractDir, binaryName),
    path.join(extractDir, 'bin', binaryName),
    path.join(extractDir, 'ffmpeg', binaryName),
    path.join(extractDir, 'ffmpeg-master-latest-win64-gpl', 'bin', binaryName),
    path.join(extractDir, 'ffmpeg-master-latest-linux64-gpl', 'bin', binaryName),
    path.join(extractDir, 'ffmpeg-master-latest-macos64-gpl', 'bin', binaryName)
  ];
  
  for (const searchPath of searchPaths) {
    if (fs.existsSync(searchPath)) {
      return searchPath;
    }
  }
  
  return null;
}

// 安装FFmpeg
async function installFFmpeg(packagePath) {
  const platform = process.platform;
  const config = PLATFORM_CONFIG[platform];
  
  const binariesDir = path.join(process.cwd(), 'binaries');
  const extractDir = path.join(binariesDir, 'temp-extract');
  const targetPath = path.join(binariesDir, config.binaryName);
  
  try {
    // 创建目录
    if (!fs.existsSync(binariesDir)) {
      fs.mkdirSync(binariesDir, { recursive: true });
    }
    
    if (!fs.existsSync(extractDir)) {
      fs.mkdirSync(extractDir, { recursive: true });
    }
    
    // 解压文件
    await extractPackage(packagePath, extractDir);
    
    // 查找FFmpeg二进制文件
    const ffmpegPath = findFFmpegBinary(extractDir, config.binaryName);
    
    if (!ffmpegPath) {
      throw new Error('无法在解压的文件中找到FFmpeg二进制文件');
    }
    
    // 复制到目标位置
    fs.copyFileSync(ffmpegPath, targetPath);
    
    // 设置执行权限（Linux/macOS）
    if (platform !== 'win32') {
      fs.chmodSync(targetPath, '755');
    }
    
    logSuccess(`FFmpeg已安装到: ${targetPath}`);
    
    // 清理临时文件
    fs.rmSync(extractDir, { recursive: true, force: true });
    
    return targetPath;
    
  } catch (error) {
    // 清理临时文件
    if (fs.existsSync(extractDir)) {
      fs.rmSync(extractDir, { recursive: true, force: true });
    }
    throw error;
  }
}

// 验证FFmpeg安装
function verifyFFmpeg(ffmpegPath) {
  try {
    logInfo('验证FFmpeg安装...');
    
    const output = execSync(`"${ffmpegPath}" -version`, { 
      encoding: 'utf8',
      timeout: 10000 
    });
    
    const versionLine = output.split('\n')[0];
    logSuccess(`FFmpeg版本: ${versionLine}`);
    
    return true;
  } catch (error) {
    logError(`FFmpeg验证失败: ${error.message}`);
    return false;
  }
}

// 主函数
async function main() {
  log('🔧 FFmpeg手动安装工具', 'bright');
  log('适用于网络下载失败的情况', 'cyan');
  console.log('');
  
  const platform = process.platform;
  const config = PLATFORM_CONFIG[platform];
  
  if (!config) {
    logError(`不支持的操作系统: ${platform}`);
    process.exit(1);
  }
  
  logInfo(`当前平台: ${platform}`);
  logInfo(`支持的格式: ${config.supportedFormats.join(', ')}`);
  console.log('');
  
  // 查找本地安装包
  logInfo('搜索本地FFmpeg安装包...');
  const packages = findLocalPackages();
  
  if (packages.length === 0) {
    logError('未找到任何FFmpeg安装包');
    console.log('');
    logInfo('请将FFmpeg安装包放在以下目录之一:');
    logInfo('  - ./ffmpeg-packages/');
    logInfo('  - ./packages/');
    logInfo('  - ./assets/');
    console.log('');
    logInfo(`支持的包名模式: ${config.searchPatterns.join(', ')}`);
    process.exit(1);
  }
  
  // 显示找到的包
  logSuccess(`找到 ${packages.length} 个FFmpeg安装包:`);
  packages.forEach((pkg, index) => {
    log(`  ${index + 1}. ${pkg.name} (${pkg.size})`, 'cyan');
  });
  console.log('');
  
  // 选择包（如果有多个）
  let selectedPackage = packages[0];
  
  if (packages.length > 1) {
    logInfo('检测到多个安装包，将使用第一个匹配的包');
    logInfo(`选择: ${selectedPackage.name}`);
    console.log('');
  }
  
  // 安装FFmpeg
  try {
    logInfo('开始安装FFmpeg...');
    const ffmpegPath = await installFFmpeg(selectedPackage.path);
    
    // 验证安装
    if (verifyFFmpeg(ffmpegPath)) {
      logSuccess('FFmpeg安装成功！');
      console.log('');
      logInfo('您现在可以运行应用程序了');
    } else {
      logError('FFmpeg安装可能有问题，请检查安装包');
      process.exit(1);
    }
    
  } catch (error) {
    logError(`安装失败: ${error.message}`);
    process.exit(1);
  }
}

// 运行主函数
if (require.main === module) {
  main().catch(error => {
    logError(`程序执行失败: ${error.message}`);
    process.exit(1);
  });
}

module.exports = { main, findLocalPackages, installFFmpeg, verifyFFmpeg }; 